package com.demo.server;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import androidx.annotation.Nullable;
import com.demo.tool.WkLog;

import com.demo.bean.EvenBusBean;
import com.demo.bean.WkHttpClient;
import com.demo.callback.ServerStateCallback;
import com.demo.tool.MyBaseFileTool;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class WkHttpServer extends Service {
    private WkHttpClient fileServer ;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }


    private ServerStateCallback serverStateCallback = new ServerStateCallback() {
        @Override
        public void onFileUploadProgress(String progress) {
            EventBus.getDefault().post( new EvenBusBean(progress , null)  );
        }

        @Override
        public void oherInfo(String msg) {
            EventBus.getDefault().post( new EvenBusBean( null , msg)  );
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        try {
            List<File> rootDirs = new ArrayList<File>();
            rootDirs.add(new File(  MyBaseFileTool.getFileBaseDir() ).getAbsoluteFile());

            fileServer =  new WkHttpClient(  8080, rootDirs ,serverStateCallback ) ;
            fileServer.start();
            serverStateCallback.oherInfo("http 服务启动...");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(fileServer!=null){
            fileServer.stop();
            WkLog.showLog("http 服务关闭...");
        }
    }
}
